const api = require('../config/api.js');
const cache = require('../services/cache.js');

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封装微信的wx.request
 * 本方法会在收到401返回码时，调用getUserInfo登陆（如果用户未授权，将会跳转授权登陆页面）
 */
function request(url, data = {}, method = "GET") {
  BarLoading();
  var redata = data;
  var contentType = 'application/json';
  if (method =="POST"){
    contentType = 'application/x-www-form-urlencoded';
  }
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        "Content-Type": contentType,
        'MINIPROGRAM-TOKEN': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log("请求："+url,redata);
        if (res.statusCode == 200) {
          if (res.data.errno == 401) {
            //需要登录后才可以操作
            try {
              wx.removeStorageSync('token');
              wx.removeStorageSync('userInfo');
            } catch (e) {
              console.log("catch:", e);
            }
            let code = null;
            return login().then((res) => {
              code = res.code;
              return getUserInfo();
            }).then((userInfo) => {
              //登录远程服务器
              request(api.AuthLoginByWeixin, { code: code, userInfo: userInfo }, 'GET').then(res => {
                if (res.errno === 0) {
                  //存储用户信息
                  wx.setStorageSync('userInfo', res.data.userInfo);
                  wx.setStorageSync('token', res.data.token);
                  resolve(res);
                } else {
                  reject(res);
                }
              }).catch((err) => {
                reject(err);
              });
            }).catch((err) => {
              reject(err);
            })
          } else {
            resolve(res.data);
            console.log('返回：', res.data);
          }
        } else {
          reject(res.errMsg);
        }
      },
      fail: function (err) {
        reject(err)
        console.log("fail" + url, err)
      },
      complete: function (res) {
        BarLoading(0);
      }
    })
  });
}

function get(url, data = {}) {
  return wxrequest(url, data, 'GET')
}

function post(url, data = {}) {
  return wxrequest(url, data, 'POST')
}
/**
 * 大卫，封装微信的wx.request
 * 本方法会在收到401返回码时，用code静默登陆。
 */
function wxrequest(url, data = {}, method = "GET") {
  BarLoading();
  //入口参数
  let _url = url;
  let _data = data;
  let _method = method;

  //临时数据
  let tmpRes = {};
  var contentType = 'application/json';
  if (method == "POST") {
    contentType = 'application/x-www-form-urlencoded';
  }
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        "Content-Type": contentType,
        'MINIPROGRAM-TOKEN': wx.getStorageSync('token')
      },
      success: function (res) {
        // 请求成功
        console.log("wx请求：" + url, _data);
        if (res.statusCode == 200) {
          if (res.data.errno == 401) {
            // 请求成功，返回未登录
            try {
              wx.removeStorageSync('token');
              wx.removeStorageSync('userInfo');
            } catch (e) {
              console.log("catch:", e);
            }
            tmpRes = res.data; //调用接口返回的 失败数据
            //需要登录后才可以操作
            let code = null;
            return login().then((res) => {
              code = res.code;
              //通过code静默登陆
              wxrequest(api.AuthLoginByWeixin, {code: code}).then(res => {
                if (res.errno === 0) {
                  //存储用户信息                  
                  wx.setStorageSync('token', res.data.token);
                  wx.setStorageSync('userInfo', res.data.userInfo);
                  resolve(tmpRes);
                } else {
                  reject(tmpRes);
                }
              }).catch((err) => {
                reject(err);
              });
            }).catch((err) => {
              reject(err);
            })
          } else {
            // 请求成功，返回成功
            resolve(res.data);
            //console.log('wx返回：', res);
            console.log('wx返回：', res.data);
            //wx.setStorageSync("PHPSESSID", res.header["Set-Cookie"]);
          }
        } else {
          // 请求成功，返回错误
          reject(res.errMsg);
        }
      },
      fail: function (err) {
        // 请求失败
        reject(err)
        console.log("failed" + url, err)
      },
      complete: function (res) {
        BarLoading(0);
      }
    })
  });
}
/**
 * 获取用户的当前设置。
 * 返回值中只会出现小程序已经向用户请求过的权限。
 */
function getSetting() {
  return new Promise(function (resolve, reject) {
    wx.getSetting({
      success: res => {
        resolve(res);
      }
    })
  });
}
/**
 * wx.login获取code
 * 【本接口会刷新sessionKey，只在必要时候用】
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          console.log(res)
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}
/**
 * @method
 * 获取用户基本信息
 * 受微信的限制，本函数需要在 <button open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo"></button> 的回调函数中调用
 * 需要先使用 <button> 弹窗，让用户接受授权，然后再安全调用 wx.getUserInfo 获取用户信息
 */
function getUserInfo() {
  return new Promise(function (resolve, reject) {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: function (res) {
              console.log(res)
              resolve(res);
            },
            fail: function (err) {
              reject(err);
            }
          })
        } else {
          //未授权，跳转登录页
          wx.navigateTo({
            url: '/pages/auth/login/login'
          })
        }
      }
    })
  });
}

function redirect(url) {
  //判断页面是否需要登录
  if (false) {
    wx.redirectTo({
      url: '/pages/auth/login/login'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}
//错误提示（有图标），最多7个汉字
function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/static/images/icon_error.png'
  })
}
//简洁提示（无图标）
function showToast(msg){
  wx.showToast({
    icon: 'none',
    title: msg,
    //mask: true
  });
}
//标题栏加载动画：开启、关闭
function BarLoading(show = 1){
  if (show === 1){
    wx.showNavigationBarLoading();
  } else {
    wx.hideNavigationBarLoading();
  }
}
//加载动画：开启、关闭
function showLoading(show = 1) {
  if (show === 1) {
    wx.showLoading({
      title: '加载中...',
    });
  } else {
    wx.hideLoading();
  }
}

function isDef(value) {
  return value !== undefined && value !== null;
}

function isObj(x) {
  var type = typeof x;
  return x !== null && (type === 'object' || type === 'function');
}

module.exports = {
  formatTime,
  request,
  redirect,
  login,
  getUserInfo,
  getSetting,
  get,
  post,
  wxrequest,
  showErrorToast,
  showToast,
  BarLoading,
  showLoading,
  isObj,
  isDef,
}